<style scoped lang="scss">
    .ke-upload__ {
        &shade {
            height: 100%;
            left: 0;
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 9999;
            background: rgba(0,0,0,0.5);
            overflow: auto;
        }
        &dialog {
            position: relative;
            border: solid 1px #eee;
            margin: 0 auto;
            margin-top: 20vh;
            width: 760px;
            background: #fff;
            z-index: 99999;
            box-shadow: 0 1px 3px rgba(0,0,0,.3);
            border-radius: 5px;

            color: #606266;
            font-size: 14px;
            margin-bottom: 40px;
        }
        &topbar {
            border-bottom: solid 1px #eee;
            list-style: none;
            margin: 0;
            padding: 10px;
            li {
                display: inline-block;
                color: #A7B1C5;
                padding: 10px 20px;
                font-size: 13px;
                cursor: pointer;
                border-radius: 4px;
                margin: 0 6px;
                &:hover {
                    background: #EEEEEE;
                }
            }
            .active {
                background: #19AA8D;
                color: #fff;
                &:hover {
                    background: #19AA8D;
                }
            }
        }
        &container {
            margin: 20px 40px;
            display: block;
        }
        &fixed {
            background: rgba(0,0,0,0.75);
            width: 100%;
            display: block;
            position: absolute;
            color: #fff;
            overflow: hidden;
            transition: all .4s;
            height: 0;
            .el-icon-delete {
                float: right;
                margin-right: 8px;
                cursor: pointer;
                &:hover {
                    color: #00C1DE;
                }
            }
        }
        &filelist {
            list-style: none;
            margin: 0;
            padding: 0;
            vertical-align: top;
            li {
                vertical-align: top;
                display: inline-block;
                width: 110px;
                height: 110px;
                margin: 5px;
                position: relative;
                &:hover {
                    .upload-fixed {
                        padding: 6px 0;
                        height: 16px;
                    }
                }
            }
            img {
                width: 100%;
                height: 100%;
            }
            & .add {
                text-align: center;
                width: 110px;
                height: auto;
                line-height: 110px;
                background: #f3f3f3;
                cursor: pointer;
            }
            .load {
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
                background: rgba(243,243,243,0.65);
            }
        }
        &icon {
            font-size: 30px;
            font-weight: bold;
            color: #fff;
        }
        &no-image {
            text-align: center;
            height: 300px;
            line-height: 300px;
        }
        &action {
            margin: 20px 40px;
            padding: 10px;
            height: 40px;
            line-height: 40px;
        }
        &progress {
            width: 300px;
            padding-top: 12px;
        }
        &fr {
            float: right;
        }
        &fl {
            float: left;
        }

        &kup-btn {
            background: #fff;
            border: solid 1px #ddd;
            padding: 6px 10px;
            cursor: pointer;
            transition: all .4s;
            outline: none;
            line-height: 20px;
        }
        &kup-btn:hover {
            opacity: .7;
        }
        &kup-btn + &kup-btn {
            margin-left: 10px;
        }
        &kup-btn.info {
            color: #fff;
            background: #19AA8D;
            border-color: #19AA8D;
        }

        &input {
            border: solid 1px #ddd;
            width: 100%;
            outline: none;
        }
        &input.text {
            resize: none;
            padding: 10px;
        }

        &select-img {
            font-size: 16px;
            padding: 15px 35px;
            border-radius: 4px;
            line-height: 45px;
        }
    }
</style>
<template>
    <section  v-if="show" class="ke-upload__shade">
        <div class="ke-upload__dialog">
            <ul class="ke-upload__topbar">
                <li :class="{ active: active === 0 }" @click="active = 0">上传图片</li>
                <li :class="{ active: active === 1 }" @click="active = 1">远程获取</li>
            </ul>

            <div class="ke-upload__container">
                <template v-if="active === 0">
                    <div class="ke-upload__no-image" v-if="files.length === 0">
                        <button class="ke-upload__kup-btn info ke-upload__select-img" @click="onSelectImage">点击选择图片</button>
                    </div>

                    <ul class="ke-upload__filelist" v-else>
                        <li v-for="file, index in files" :key="index">
                            <span v-if="(uploading && successing.indexOf(file.lastModified) === -1)" class="load">
                            </span>
                            <span class="ke-upload__fixed" @click="onRemove(index)" v-if="!uploading">
                                <i class="el-icon-delete"></i>
                            </span>
                            <img :src="showDataUri(file)"/>
                        </li>
                    </ul>
                </template>


                <!-- 远程下载 -->
                <template v-else>
                    <textarea class="ke-upload__input text" v-if="multiple" v-model="urls" rows="15" placeholder="每行一个地址"></textarea>
                    <input v-else v-model="urls"/>
                </template>
            </div>

            <div class="ke-upload__action">
                <progress v-if="uploading" class="ke-upload__progress fl" color="#1989FA" :text-inside="true" :stroke-width="18" :percentage="jd"></progress>


                <div v-else class="ke-upload__fl">
                    <span v-if="multiple">选中{{ files.length }}张图片，</span>

                    <span>共{{ sizes }}</span>
                </div>

                <div class="ke-upload__fr">
                    <button type="button" class="ke-upload__kup-btn add" @click="onSelectImage" v-if="multiple && files.length > 0">继续添加</button>

                    <button type="button" class="ke-upload__kup-btn info" @click="onStartUpload" v-if="!uploading">确定使用</button>

                    <button type="button" class="ke-upload__kup-btn" @click="close">取消</button>
                </div>
            </div>
        </div>
    </section>
</template>

<script>
    export default {
        props: {
            display: Boolean,
            multiple: Boolean,
            request: Function,
            callback: Function
        },
        data () {
            return {
                active: 0,
                show: false,
                files: [],
                uploading: false,
                jd: 0,
                successing: [],
                count: 3,
                module: 'default',
                urls: ''
            }
        },
        watch: {
            display (v) {
                this.show = v
            }
        },
        computed: {
            /**
             * 文件大小
             */
            sizes () {
                let s = this.sizes_n
                if (s > 1024000) {
                    return (s / 1024000).toFixed(2) + 'Mb'
                } else {
                    return (s / 1024).toFixed(2) + 'Kb'
                }
            },
            sizes_n () {
                let s = 0
                for (let file of this.files) {
                    s = s + file.size
                }
                return s
            }
        },
        methods: {

            /**
             * 选择图片
             */
            onSelectImage () {
                let fs = document.createElement('input')
                fs.setAttribute('type', 'file')
                fs.setAttribute('accept', 'image/*')
                if (this.multiple) {
                    fs.setAttribute('multiple', 'multiple')
                }
                fs.onchange = (data) => {
                    let fs = []
                    for (let file of data.target.files) {
                        fs.push(file.lastModified)
                    }
                    let index = this.files.findIndex(file => {
                        return fs.indexOf(file.lastModified) !== -1
                    })
                    if (index !== -1) {
                        return alert('不能重复上传图片')
                    }
                    for (let file of data.target.files) {
                        this.files.push(file)
                    }
                }
                this.$nextTick(() => {
                    fs.click()
                })
            },

            /**
             * 删除这张图片
             * @param index
             */
            onRemove (index) {
                this.files.splice(index, 1)
            },


            showDataUri (file) {
                if(typeof window.createObjectURL !== 'undefined'){
                    return window.createObjectURL(file)
                }else if(typeof window.URL !== 'undefined'){
                    return URL.createObjectURL(file)
                }else if(typeof window.webkitURL !== 'undefined'){
                    return webkitURL.createObjectURL(file)
                }
            },


            /**
             * 上传
             */
            uploadFile () {
                let fs = this.files
                let index = 0
                let task = []
                let sizes = 0
                let success = 0

                let timer = setInterval(() => {
                    if (typeof fs[index] === 'undefined') {
                        clearInterval(timer)
                        return
                    }
                    if (task.length < this.count) {
                        let file = fs[index]
                        file.status = 0
                        console.log('=============开始上传', file.name)
                        // 加入任务队列
                        task.push(file.lastModified)
                        let fd = new FormData()
                        fd.append('file', file)
                        this.request(file, {
                            module: this.module,
                            timeout: 60 * 3 * 1000
                        }, (jd) => {
                            sizes += jd.loaded
                            let j = ((sizes / this.sizes_n) * 100).toFixed(0)
                            // this.jd = Math.ceil(sizes / this.sizes_n) * 100
                            this.jd = parseInt(j)
                        }).then(result => {
                            let sindex = task.findIndex(t => {
                                return t === file.lastModified
                            })
                            file.status = 1
                            task.splice(sindex, 1)
                            success++
                            if (result.code) {
                                this.successing.push(file.lastModified)
                                file.result = result
                            } else {
                                this.warning(result.error)
                            }
                            if (success === this.files.length) {
                                this.success()
                            }
                        })
                        index++
                    }

                }, 100)
            },



            /**
             * 远程获取
             */
            downloadFile () {
                let urls = this.urls.split(/[\s\n]/)
                urls.map(url => {
                    if (url.trim() !== '') {
                        this.files.push({
                            name: '远程下载',
                            url: url,
                            stauts: 0
                        })
                    }
                })
                let fs = this.files
                let index = 0
                let task = []
                let sizes = 0
                let success = 0

                let timer = setInterval(() => {
                    if (typeof fs[index] === 'undefined') {
                        clearInterval(timer)
                        return
                    }
                    if (task.length < this.count) {
                        let file = fs[index]
                        file.status = 0
                        console.log('=============开始下载', file.url)
                        // 加入任务队列
                        task.push(file.url)
                        this.request('download', {
                            url: this.apiUrl,
                            data: { url: file.url },
                            timeout: 60 * 3 * 1000,
                            onUploadProgress: (jd) => {
                                sizes += jd.loaded
                                let j = ((sizes / this.sizes_n) * 100).toFixed(0)
                                // this.jd = Math.ceil(sizes / this.sizes_n) * 100
                                this.jd = parseInt(j)
                            }
                        }).then(result => {
                            let sindex = task.findIndex(t => {
                                return t === file.url
                            })
                            file.status = 1
                            task.splice(sindex, 1)
                            success++
                            this.jd = Math.ceil(success / this.files.length * 100)
                            if (result.code) {
                                this.successing.push(file.url)
                                file.result = result
                            } else {
                                this.warning(result.error)
                            }
                            if (success === this.files.length) {
                                this.success()
                            }
                        })
                        index++
                    }

                }, 100)
            },


            /**
             * 开始上传
             */
            onStartUpload () {
                this.uploading = true
                if (this.active === 0) {
                    this.uploadFile()
                } else {
                    this.downloadFile()
                }
            },


            /**
             * 上传完毕
             */
            success () {
                if (this.multiple) {
                    let result = []
                    for (let file of this.files) {
                        if (file.result) {
                            result.push(file.result)
                        }
                    }
                    this.callback && this.callback(result)
                } else {
                    this.callback && this.callback(this.files[0].result)
                }
                this.close()
            },

            /**
             * 关闭
             */
            close () {
                this.show = false
                this.$emit('update:display', false)
                this.$nextTick(() => {
                    this.successing = []
                    this.files = []
                    this.urls = ''

                    this.uploading = false
                    this.jd = 0
                })
            }
        },
        mounted () {
        }

    }
</script>
